package com.hulman.oms.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.hulman.oms.bean.Patrol;
import com.hulman.oms.bean.PatrolReport;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.User;
import com.hulman.oms.dao.PatrolReportDao;
import com.hulman.oms.util.DateUtil;
import com.hulman.oms.util.StringUtil;
import com.hulman.oms.util.SubjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @Author: maxwellens
 */
@Service
@Slf4j
public class PatrolReportService
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private PatrolReportDao patrolReportDao;
    @Autowired
    private PatrolService patrolService;
    @Autowired
    private OnlyOfficeService onlyOfficeService;
    @Autowired
    private OllamaChatModel ollamaChatModel;

    public List<PatrolReport> findPatrolReports(Map<String, Object> map)
    {
        return patrolReportDao.findPatrolReports(map);
    }

    public Integer findPatrolReportsCount(Map<String, Object> map)
    {
        return patrolReportDao.findPatrolReportsCount(map);
    }

    public Result findPatrolReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = patrolReportDao.findPatrolReportsCount(map);
        List<PatrolReport> data = patrolReportDao.findPatrolReports(map);
        return new Result(data, count);
    }

    public PatrolReport findPatrolReportById(Integer id)
    {
        return patrolReportDao.findPatrolReportById(id);
    }

    public void savePatrolReport(PatrolReport patrolReport)
    {
        if (patrolReport.getId() != null && patrolReport.getId() != 0)
        {
            patrolReportDao.updatePatrolReport(patrolReport);
        } else
        {
            patrolReportDao.insertPatrolReport(patrolReport);
        }
    }

    public void deletePatrolReportById(Integer id)
    {
        patrolReportDao.deletePatrolReportById(id);
    }

    public void deletePatrolReports(int[] ids)
    {
        patrolReportDao.deletePatrolReports(ids);
    }

    public void createPatrolReport(Date date)
    {
        String patrolContent = patrolService.getPatrolContents(date);
        String prompt = "帮我总结和概括以下内容,内容不超过100个字：" + patrolContent;
        ChatResponse chatResponse = ollamaChatModel.call(new Prompt(prompt));
        String content = chatResponse.getResults().get(0).getOutput().getText();
        log.info("prompt:{}", prompt);
        log.info("content:{}", content);
        PatrolReport patrolReport = new PatrolReport();
        patrolReport.setContent(content);
        patrolReport.setState(0);
        patrolReport.setCreateDate(date);
        patrolReportDao.insertPatrolReport(patrolReport);
    }

    public void generate(PatrolReport patrolReport) throws IOException
    {
        User user = SubjectUtil.getUser();
        patrolReport.setCreateById(user.getId());
        patrolReport.setCreateByName(user.getName());

        Map<String, Object> map = new HashMap<>();
        Date createDate = patrolReport.getCreateDate();
        map.put("startDate", DateUtil.toDate(createDate));
        map.put("endDate", DateUtil.toDate(createDate));
        List<Patrol> patrols = patrolService.findPatrols(map);
        Collections.reverse(patrols);
        for (int i = 0; i < patrols.size(); i++)
        {
            Patrol patrol = patrols.get(i);
            patrol.setSn(i + 1);
        }
        //生成报表
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/patrol-report.xlsx");
        String fileId = StringUtil.uuid() + ".xlsx";
        Path filePath = Paths.get(fileHome, fileId);
        OutputStream outputStream = Files.newOutputStream(filePath);
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(patrols, fillConfig, writeSheet);
        Map<String, Object> head = new HashMap<>();
        head.put("createDate", DateUtil.toDate(createDate));
        head.put("createByName", user.getName());
        excelWriter.fill(head, writeSheet);
        excelWriter.finish();
        patrolReport.setFileId(fileId);
        patrolReport.setState(1);
        patrolReportDao.updatePatrolReport(patrolReport);
        String fileName = DateUtil.toChineseDate(createDate) + "巡检日报.xlsx";
        onlyOfficeService.create(fileId, fileName);
    }

    public void submitPatrolReport(PatrolReport patrolReport)
    {
        User user = SubjectUtil.getUser();
        patrolReport.setCreateById(user.getId());
        patrolReport.setCreateByName(user.getName());
        patrolReport.setState(2);
        patrolReportDao.updatePatrolReport(patrolReport);
    }
}
